import {
  Injectable,
  Inject,
  forwardRef,
  UnauthorizedException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './entities/user.entity';

import { Request } from 'express';
import { WechatService } from '@/common/platform/wechat/wechat.service';
import { RedisService } from '@/common/redis/redis.service';
import { JwtService } from '@nestjs/jwt';
import { GetWechatPhoneDto } from '@/common/platform/wechat/dto/get-phone.dto';
import { UploadService } from '@/common/upload/upload.service';
import { Express } from 'express';
import { WechatConfig } from '@/config/wechat.config';
@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
    @Inject(forwardRef(() => WechatService))
    private readonly wechatService: WechatService,
    private readonly redisService: RedisService,
    private readonly jwtService: JwtService,
    private readonly UploadService: UploadService,
  ) {}

  async createUser(
    code: string,
    req: Request,
  ): Promise<User & { token: string }> {
    // 获取微信用户信息
    const wechatUser = await this.wechatService.create(code);
    const isWechat = req?.headers['x-auth-source'] === 'wechat';

    // 检查是否是微信来源
    if (!code) {
      throw new UnauthorizedException('没有code');
    }
    if (!isWechat) {
      throw new UnauthorizedException('无法登陆，请检查环境');
    }
    // 查找或创建用户
    let user = await this.userRepository.findOne({
      where: { openId: wechatUser.openid },
    });

    if (!user) {
      user = this.userRepository.create({
        openId: wechatUser.openid,
        sessionKey: wechatUser.session_key,
        nickName:
          WechatConfig.apps.defaultNickName +
          Math.random().toString(36).substring(2, 7),
      });
      user = await this.userRepository.save(user);
    }

    // 生成JWT并存入Redis
    const token = this.jwtService.sign({
      sub: user.id,
      openid: user.openId,
    });
    await this.redisService.setUserToken(user, token);

    return { ...user, token };
  }

  async getUserPhone(info: GetWechatPhoneDto, token: string) {
    // 解析token获取用户信息
    const payload = this.jwtService.verify(token);
    const openid = payload.openid as string;
    const userInfo: User = await this.redisService.getUserToken(openid);
    // 获取手机号
    const { phone } = this.wechatService.getWechatBindPhone({
      ...info,
      sessionKey: userInfo.sessionKey,
    });

    // 更新用户手机号到数据库
    await this.userRepository.update({ id: userInfo.id }, { mobile: phone });
    return { success: true };
  }

  async getUserNickName(info: GetWechatPhoneDto, token: string) {
    // 解析token获取用户信息
    const payload = this.jwtService.verify(token);
    const openid = payload.openid as string;
    const userInfo: User = await this.redisService.getUserToken(openid);
    // 获取手机号
    const { nickName } = this.wechatService.getWechatBindNickName({
      ...info,
      sessionKey: userInfo.sessionKey,
    });

    // 更新用户手机号到数据库
    await this.userRepository.update(
      { id: userInfo.id },
      { nickName: nickName },
    );
    return { success: true };
  }
  /**
   *  获取用户头像
   * @param openId 用户的openId
   */
  async updateUserAvatar(file: Express.Multer.File, openId: string) {
    const prefixPath = `${process.env.WECHAT_APP_TYPE}/user_avator/${process.env.NODE_ENV}_${process.env.WECHAT_APPID}_${openId}`;
    const userInfo: User = await this.redisService.getUserToken(openId);
    const { url } = await this.UploadService.uploadFile(file, prefixPath);
    console.log('userInfo', userInfo);
    // 更新用户头像URL到数据库
    await this.userRepository.update(
      { openId: userInfo.openId },
      { avatar: url },
    );

    return url; // 直接返回图片URL
  }
}
